import { Service } from "egg";
import { Types } from "mongoose";
import { RoleProps } from "../model/Role";
import { RoleGroupProps } from "../model/RoleGroup";

export default class RoleService extends Service {
  /**
   * 根据传入名称查询
   */
  public findByName(role_name: string) {
    return this.ctx.model.Role.findOne({ role_name });
  }

  /**
   * 角色列表查找
   */
  public findList() {
    const { ctx } = this;
    return ctx.model.RoleGroup.aggregate([
      {
        $lookup: {
          from: "roles",
          localField: "_id",
          foreignField: "role_group_id",
          as: "roles",
        },
      },
    ]);
  }

  /**
   * 角色添加
   * @param data 测试数据
   */
  public async add(data) {
    const { ctx } = this;
    const { user: userInfo } = ctx.state;
    const _data: Partial<RoleProps> = {
      ...data,
      company_id: Types.ObjectId(userInfo.company),
    };
    return await ctx.model.Role.create(_data);
  }

  /**
   * 角色修改
   */
  public update(id, data) {
    const { ctx } = this;
    const payload: Partial<RoleProps> = {
      ...data,
    };
    return ctx.model.Role.findOneAndUpdate({ id }, payload, {
      new: true,
    }).lean();
  }

  /**
   * 角色分组修改
   * @param data 测试数据
   */
  public async groupUpdate(data) {
    const { ctx } = this;
    const _data: Partial<RoleGroupProps> = {
      ...data,
    };
    return await ctx.model.RoleGroup.updateOne(_data);
  }

  /**
   * 根据角色查询权限列表
   * @param {number} id 角色ID
   */
  public async selectRolePrivileges(id) {
    const { ctx } = this;
    const _roleInfo = await ctx.model.Role.findOne({ id });
    if (!_roleInfo) {
      throw new Error("该角色新不存在");
    }
    let _list = await ctx.model.PrivilegesType.aggregate([
      {
        // 链表
        $lookup: {
          from: "privileges",
          localField: "_id",
          foreignField: "privileges_type_id",
          as: "privileges",
        },
      },
      {
        // 筛选连表的查询字段
        $project: {
          id: 1,
          privileges_type_name: 1,
          privileges_type_code: 1,
          is_delete: 1,
          privileges: {
            _id: 1,
            id: 1,
            is_delete: 1,
            privileges_name: 1,
            privileges_url: 1,
          },
        },
      },
    ]);
    if (_list.length === 0) {
      _list = [];
    } else {
      _list.forEach((item) => {
        item.privileges.forEach((v: any) => {
          if (_roleInfo.role_name === "所有者") {
            v.has_privilege = 1;
          } else {
            if (
              _roleInfo.privileges_id.length > 0 &&
              // eslint-disable-next-line @typescript-eslint/ban-ts-comment
              // @ts-ignore
              _roleInfo.privileges_id.includes(v.id)
            ) {
              v.has_privilege = 1;
            } else {
              v.has_privilege = 0;
            }
          }
        });
      });
    }
    return _list;
  }

  /**
   * 根据名称查询角色分组
   * @param role_group_name 角色分组名称
   */
  public groupFindByName(role_group_name: string) {
    return this.ctx.model.RoleGroup.findOne({ role_group_name });
  }

  /**
   * 角色分组添加
   * @param data 需要添加的数据
   */
  public async groupAdd(data) {
    const { ctx } = this;
    const _data: Partial<RoleGroupProps> = {
      ...data,
    };
    return await ctx.model.RoleGroup.create(_data);
  }
}
